package com.mezz.bones.im.logic.repository.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mezz.bones.im.logic.mapper.IChatUserRemarkMapper;
import com.mezz.bones.im.logic.domain.entity.ChatUserRemark;
import com.mezz.bones.im.logic.repository.IChatUserRemarkRepository;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * IM用户 服务实现类
 * </p>
 *
 * @author mezz
 * @since 2025-04-28
 */
@Service
public class ChatUserRemarkRepositoryImpl extends ServiceImpl<IChatUserRemarkMapper, ChatUserRemark> implements IChatUserRemarkRepository {

    @Override
    public String getPeerRemarkNickname(String userId, String peerId) {

        LambdaQueryWrapper<ChatUserRemark> q = new LambdaQueryWrapper<>();
        q.select(ChatUserRemark::getRemarkName);
        q.eq(ChatUserRemark::getUserId,userId);
        q.eq(ChatUserRemark::getPeerId,peerId);
        ChatUserRemark one = getOne(q);
        if(one == null){
            return "";
        }

        return one.getRemarkName();
    }

    @Override
    public ChatUserRemark getByUserIdAndPeerId(String userId, String peerId) {

        LambdaQueryWrapper<ChatUserRemark> q = new LambdaQueryWrapper<>();
        q.eq(ChatUserRemark::getUserId,userId);
        q.eq(ChatUserRemark::getPeerId,peerId);
        return getOne(q);
    }

    /**
     * 批量查询用户userId 对 目标用户群 peerIds 的备注信息
     * @param userId
     * @param peerIds
     * @return key:peerId value:备注 如果没有备注 则不存储peerId
     */
    @Override
    public Map<String,String> findPeersRemarkNickname(String userId, List<String> peerIds) {

        if(CollUtil.isEmpty(peerIds)){
            return new HashMap<>();
        }

        LambdaQueryWrapper<ChatUserRemark> q = new LambdaQueryWrapper<>();
        q.select(ChatUserRemark::getUserId,ChatUserRemark::getPeerId,ChatUserRemark::getRemarkName);
        q.eq(ChatUserRemark::getUserId,userId);
        q.in(ChatUserRemark::getPeerId,peerIds);
        List<ChatUserRemark> list = list(q);
        return list.stream().collect(Collectors.toMap(
                ChatUserRemark::getPeerId,
                ChatUserRemark::getRemarkName
        ));
    }

    @Override
    public void clearRemarkName(String userId, String peerId) {

        LambdaUpdateWrapper<ChatUserRemark> del = new LambdaUpdateWrapper<>();
        del.eq(ChatUserRemark::getUserId,userId);
        del.eq(ChatUserRemark::getPeerId,peerId);
        del.set(ChatUserRemark::getUpdateTime,new Date());
        del.set(ChatUserRemark::getIsDel,1);
        this.update(del);
    }
}
